import { asyncRoutes, currencyRoutes } from '@/router'

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES(state, routes) {
    state.routes = [...currencyRoutes, ...routes]
    state.addRoutes = routes
  }
}


/**
 * 判断是否有权限
 * @param permissions
 * @param route
 */
function hasPermission(permissions, route) {
  if (route.meta && route.meta.sign) {
    return permissions.includes(route.meta.sign)
  } else {
    return true
  }
}


/**
 * 遍历asyncRoutes动态路由(通过权限值去过滤出有权限的路由)
 * @param route
 * @param permissions
 * @returns {[]}
 */
function filterAsyncRoutes(route, permissions) {
  let arrNew = []
  for (let item of route) {
    let itemNew = { ...item } // 解决浅拷贝共享同一内存地址
    if (hasPermission(permissions, itemNew)) {
      if (itemNew.children) {
        itemNew.children = filterAsyncRoutes(itemNew.children, permissions)
      }
      arrNew.push(itemNew)
    }
  }
  return arrNew
}


const actions = {
  /**
   * 根据permissions权限编码列表，过滤出适合权限的路由
   * @param commit
   * @param rootGetters
   * @param permissions
   * @returns {Promise<unknown>}
   */
  getAsyncRoutes({ commit, rootGetters }, permissions) {
    return new Promise(resolve => {
      let accessedRoutes
      // 如果是admin，则默认为管理员用户，拥有所有菜单路由
      if (rootGetters.userName === 'admin') {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, permissions)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
